package com.fyakm.javaprojectanalysis.controller;

import com.fyakm.javaprojectanalysis.common.base.F_Package;
import com.fyakm.javaprojectanalysis.common.conf.TechnologyConf;
import com.fyakm.javaprojectanalysis.common.util.JavaFileParserUtil;
import com.fyakm.javaprojectanalysis.common.util.XmindUtil;
import com.fyakm.javaprojectanalysis.common.util.ZipUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;


/**
 * 解析java controller层
 *      将文件压缩成zip的格式上传至服务器，服务器解析zip文件到一个零时目录下，然后通过JavaFileParserUtil解析该目录，并生成对应Xmind文件（类脑图）和txt（导包）文件。
 */
@RestController
@RequestMapping( "/test")
public class JavaParserController {

    /**
     * 将文件压缩成zip的格式上传至服务器，服务器解析zip文件到一个零时目录下，然后通过JavaFileParserUtil解析该目录，
     * 并生成对应Xmind文件（类脑图）和txt（导包）文件,将这两个文件打包压缩到新的zip中。
     */
    //返回页面
    private static final String TEMP_DIRECTOR = "\\temp\\";

    @Autowired
    private TechnologyConf technologyConf;

    /**
     * 解压xxx.zip文件到服务器目录下，TEMP_DIRECTOR，解析成项目文件xxx,将项目文件解析到xxx_result目录，包含xxx.xmind、xxx_importList.txt，打包xxx_result成xxx_result.zip返回
     * @param file
     * @return
     */
    @PostMapping("unZip")
    public String unZip(@RequestParam("file") MultipartFile file, HttpServletResponse response){

        List<String> technology = technologyConf.getTechnology();
        System.out.println(technology);

        try {
            // xxx.zip
            String originalFilename = file.getOriginalFilename();
            // xxx
            String projectPath = file.getOriginalFilename().replaceAll(".zip","");
            // C:\Users\fyakm\Desktop\temp\xxx.zip
            String tempOriginalFile = TEMP_DIRECTOR + originalFilename;
            // C:\Users\fyakm\Desktop\temp\xxx
            String projectAbsolutPath = tempOriginalFile.replaceAll(".zip","");
            // C:\Users\fyakm\Desktop\temp\xxx_result
            String result_directory = projectAbsolutPath+"_result";
            ZipUtil.unzip(file.getInputStream(),TEMP_DIRECTOR+projectPath+"\\");
            File resultDir = new File(result_directory);
            resultDir.mkdir();
            F_Package aPackage = JavaFileParserUtil.getPackage(new File(projectAbsolutPath));
            XmindUtil.generatorXmind(aPackage,result_directory+"\\"+projectPath+".xmind",true);
            JavaFileParserUtil.exportImportPackageToTxt(new File(projectAbsolutPath),result_directory+"\\"+projectPath+"export.txt");
            // 将xxx_result目录打包成xxx_result.zip
            ZipUtil.zipDirectory(result_directory,result_directory+".zip");
            downLoad(result_directory+".zip",response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "success";
    }


    private void downLoad(String filePath,HttpServletResponse response){
        response.setContentType("application/octet-stream");
        response.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
        response.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
        response.setCharacterEncoding("utf-8");
//        response.setHeader("Content-disposition", "attachment;filename=" + filePath);

        String formFileName = "";
        try {
            formFileName = new String(filePath.getBytes("UTF-8"), "ISO-8859-1");
            // 将路径去掉，只留下项目名称
            String[] split = formFileName.split("[/\\\\]");
            if(split.length>1)formFileName = split[split.length-1];
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition",String.format("attachment; filename=\"%s\"", formFileName));
        ServletOutputStream outputStream = null;
        FileInputStream inputStream = null;
        File file = new File(filePath);
        try {
            outputStream = response.getOutputStream();
            inputStream = new FileInputStream(file);
            byte[] bytes = new byte[2048];
            while (inputStream.read(bytes)!= -1){
                outputStream.write(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(outputStream!= null){
                    outputStream.close();
                }
                if(inputStream!= null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
